package CheckFile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class OverWrite {
	
	private static String fileD="./bin/HanLP.properties";
	
	protected static String FindHanlpFile(){
		
		String str=null;		 
		try{
			FileInputStream fis = new FileInputStream(fileD);
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);
			String line = "";
			while((line = br.readLine()) != null){
					int marklocation = line.indexOf("：");
					str = line.substring(marklocation+1, line.length());
					if(str.contains("root=")){
						break;				
					}
			}		
			br.close();		
		}catch(IOException e){
			e.printStackTrace();
		}
		return str;
	}
	
	protected static String ReadHanlpFile(){
		
		StringBuffer str = new StringBuffer();
		String line = null;
		try {
		   BufferedReader reader = new BufferedReader(new FileReader(fileD));
		   while ((line = reader.readLine()) != null) {
			   str.append(line + "\n");
		   }
		   	   reader.close();
		} catch (FileNotFoundException e) {
		   e.printStackTrace();
		} catch (IOException e) {
		   e.printStackTrace();
		}
		  return str.toString();
	}
	 
	protected static String ChangeHanLPFilePathInfo(){
		
		String sourcePath = FindHanlpFile();
		String nowPath = "root="+System.getProperty("user.dir").replaceAll("\\\\", "/");
		String str = ReadHanlpFile();
		str = str.replaceAll(sourcePath, nowPath);	
		return str;
		
	}
	
	public static boolean OverWriteHanLPFile(){
		
		String str = ChangeHanLPFilePathInfo();		
		try {		
			FileWriter fw = new FileWriter(fileD); //第二个参数true表示以追加形式写文件  				
			BufferedWriter bufw=new BufferedWriter(fw);		
			String s[]=str.split("\n");
			for(int i=0;i<s.length;i++){
				bufw.write(s[i]);
				bufw.newLine();
			}
			bufw.close(); 
			fw.close();
			return true;		 
		 }catch (IOException e) {
			 e.printStackTrace();
			 return false;
		 }
	
	}

}
